package a66weding.com.jiehuntong.activity;

import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.tencent.smtt.export.external.interfaces.WebResourceError;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.activity.home.BaseHomeActivity;
import a66weding.com.jiehuntong.application.DataWareHourse;
import a66weding.com.jiehuntong.beans.ErrorBean;
import a66weding.com.jiehuntong.beans.HttpRequestBean;
import a66weding.com.jiehuntong.beans.ShareInviteBean;
import a66weding.com.jiehuntong.beans.SuccessBean;
import a66weding.com.jiehuntong.common.api.Url;
import a66weding.com.jiehuntong.common.utils.CUtils;
import a66weding.com.jiehuntong.common.utils.CacheUtils;
import a66weding.com.jiehuntong.common.utils.FileUtil;
import a66weding.com.jiehuntong.common.utils.Tools;
import a66weding.com.jiehuntong.common.utils.Utils;
import a66weding.com.jiehuntong.common.utils.x5Util.X5WebView;
import a66weding.com.jiehuntong.http.HttpHandleUtil;
import a66weding.com.jiehuntong.http.OnNetResultListener;
import a66weding.com.jiehuntong.http.RequestCode;
import a66weding.com.jiehuntong.view.ConfirmLoginDialog;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;

import static a66weding.com.jiehuntong.pager.BasePager.mActivity;

/**
 * 电子请柬界面
 */
public class ElectronicInvitationActivity extends BaseHomeActivity implements View.OnClickListener, OnNetResultListener {
    private ImageView img_back;
    private ImageView img_music;
    private LinearLayout llay_information;
    private LinearLayout llay_theme_settings;
    private LinearLayout llay_write_story;
    private LinearLayout llay_guests;
    private ImageView img_share;
    private X5WebView webView;
    private WebSettings settings;
    private Context context;
    private boolean isNeedRefresh = false;
    private boolean isResume;
    /**
     * 广播用来刷新请柬界面
     */
    public static final String ACTION_REFRESH_INVITATION = "a66weding.com.jiehuntong.invitation";
    private ShareInviteBean shareInviteBean;
    private RelativeLayout demonstrateRl;// 演示布局
    private ImageView demonstrateIv01;// 新人信息
    private ImageView demonstrateIv02;// 主题设置
    private ImageView demonstrateIv03;// 谱写故事
    private ImageView demonstrateIv04;// 宾客统计
    private Button nextStepButton;// 下一步
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_electronic_invitation);
        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        context = this;
        initView();
        loadData("001");
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_REFRESH_INVITATION);
        registerReceiver(myReceiver, filter);
    }
    private void initView() {
        img_share = (ImageView) findViewById(R.id.img_share);
        img_back = (ImageView) findViewById(R.id.img_back);
        img_music = (ImageView) findViewById(R.id.img_music);
        llay_guests = (LinearLayout) findViewById(R.id.llay_guests);
        llay_information = (LinearLayout) findViewById(R.id.llay_information);
        llay_theme_settings = (LinearLayout) findViewById(R.id.llay_theme_settings);
        llay_write_story = (LinearLayout) findViewById(R.id.llay_write_story);
        img_share.setOnClickListener(this);
        img_music.setOnClickListener(this);
        img_back.setOnClickListener(this);
        llay_guests.setOnClickListener(this);
        llay_write_story.setOnClickListener(this);
        llay_theme_settings.setOnClickListener(this);
        llay_information.setOnClickListener(this);
        webView = (X5WebView) findViewById(R.id.x5_webview);
        settings = webView.getSettings();
        // 支持javascript
        settings.setJavaScriptEnabled(true);
        // 设置可以支持缩放
        settings.setSupportZoom(true);
        settings.setBuiltInZoomControls(true);
        // 不显示缩放按钮
        settings.setDisplayZoomControls(false);
        settings.setUseWideViewPort(true);
        // 自适应屏幕
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setLoadWithOverviewMode(true);
        if (Utils.checkNet(this)) {
            settings.setCacheMode(WebSettings.LOAD_DEFAULT);
        } else {
            settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        }
        webView.setWebViewClient(new WebViewClient() {// 回调网页加载的生命周期

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (isForeground(ElectronicInvitationActivity.this,"ElectronicInvitationActivity")){
                    webView.loadUrl("javascript:autoPlayMusic("+"true"+")");
                }else {
                    webView.loadUrl("javascript:autoPlayMusic("+"false"+")");
                }
        }
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if(url.startsWith("http") || url.startsWith("https")){
                    if(url.contains("http://api.map.baidu.com")){
                        Intent intent = new Intent(context, WebViewActvity.class);
                        intent.putExtra("urlPath", url);
                        intent.putExtra("title", "婚礼举办地");
                        intent.putExtra("share", false);
                        context.startActivity(intent);
                        return true;
                    }
                    settings.setCacheMode(WebSettings.LOAD_DEFAULT);
                    view.loadUrl(url);
                    return true;
                } else if(url.startsWith("tel:")){
                    if(!url.replace("tel:", "").equals("")){
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        startActivity(intent);
                    }
                    return true;
                } else {
                    return super.shouldOverrideUrlLoading(view, url);
                }
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                CUtils.showToast("加载失败，正在重试");
                isNeedRefresh=true;
                setData();
            }
        });


        demonstrateRl = (RelativeLayout) findViewById(R.id.demonstrate_rl);
        demonstrateIv01 = (ImageView) findViewById(R.id.demonstrate_iv01);
        demonstrateIv02 = (ImageView) findViewById(R.id.demonstrate_iv02);
        demonstrateIv03 = (ImageView) findViewById(R.id.demonstrate_iv03);
        demonstrateIv04 = (ImageView) findViewById(R.id.demonstrate_iv04);
        nextStepButton = (Button) findViewById(R.id.next_stup_button);
        boolean isDemonstrated = CacheUtils.getBooleanFromCache(ElectronicInvitationActivity.this, "isDemonstrated_myInvitation");
        if(!isDemonstrated){
            demonstrateRl.setVisibility(View.VISIBLE);
            demonstrateIv01.setVisibility(View.VISIBLE);
        } else {
            demonstrateRl.setVisibility(View.GONE);
        }
        nextStepButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(demonstrateIv01.getVisibility() == View.VISIBLE){
                    demonstrateIv01.setVisibility(View.GONE);
                    demonstrateIv02.setVisibility(View.VISIBLE);
                    demonstrateIv03.setVisibility(View.GONE);
                    demonstrateIv04.setVisibility(View.GONE);
                } else if(demonstrateIv02.getVisibility() == View.VISIBLE){
                    demonstrateIv01.setVisibility(View.GONE);
                    demonstrateIv02.setVisibility(View.GONE);
                    demonstrateIv03.setVisibility(View.VISIBLE);
                    demonstrateIv04.setVisibility(View.GONE);
                } else if(demonstrateIv03.getVisibility() == View.VISIBLE){
                    demonstrateIv01.setVisibility(View.GONE);
                    demonstrateIv02.setVisibility(View.GONE);
                    demonstrateIv03.setVisibility(View.GONE);
                    demonstrateIv04.setVisibility(View.VISIBLE);
                } else if(demonstrateIv04.getVisibility() == View.VISIBLE){
                    demonstrateRl.setVisibility(View.GONE);
                    CacheUtils.setBooleanToCache(ElectronicInvitationActivity.this, "isDemonstrated_myInvitation", true);
                }
            }
        });
    }


    /**
     * 判断某个界面是否在前台
     *
     * @param context
     * @param className
     *            某个界面名称
     */
    private boolean isForeground(Context context, String className) {
        if (context == null || TextUtils.isEmpty(className)) {
            return false;
        }
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        if (list != null && list.size() > 0) {
            ComponentName cpn = list.get(0).topActivity;
            if (className.equals(cpn.getClassName().substring(cpn.getClassName().lastIndexOf(".")+1,cpn.getClassName().length()))) {
                return true;
            }
        }

        return false;
    }
    /**
     * 获取分享信息
     */
    private void loadData(String requestCode) {
        int uId = DataWareHourse.getInstance().getmUser().getData().get(0).getI_Id();
        String url = Url.GETSHARELINK + "&uid=" + uId;
        HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.GETREQUEST, url,
                ElectronicInvitationActivity.this, ShareInviteBean.class, requestCode);
        HttpHandleUtil.executeCommonGet(context, httpRequestBean);
        if (requestCode.equals("001")) {
            Tools.showWaitDialog(this, "努力加载中...", true);
        }
    }

    @Override
    public void onSucess(SuccessBean sucessbean) {
        Tools.dismissWaitDialog();
        Object data = sucessbean.getData();
        if (data instanceof ShareInviteBean) {
            ShareInviteBean response = (ShareInviteBean) data;
            if (response != null && response.getResCode() != null) {
                if (response.getResCode().equals("0000")) {
                    // 界面关联数据
                    shareInviteBean = response;
                    if (sucessbean.getInf().equals("001")) {
                        isNeedRefresh = true;
                        setData();
                    }
                } else {
                    CUtils.showToast(response.getMsg());
                }
            }
        }
    }
    @Override
    public void onError(ErrorBean errorBean) {
        Tools.dismissWaitDialog();
        CUtils.showToast("数据请求失败");
    }
    @Override
    protected void onResume() {
        super.onResume();
        isResume = true;
        if (webView!=null){
            webView.loadUrl("javascript:autoPlayMusic("+"true"+")");
        }
        setData();
    }

    @Override
    protected void onPause() {
        super.onPause();
        isResume = false;
        isNeedRefresh=false;
        Tools.dismissWaitDialog();
        if (webView != null){
            webView.loadUrl("javascript:autoPlayMusic("+"false"+")");
        }
    }

    private void setData() {
        if (isNeedRefresh) {
            if (shareInviteBean != null) {
                webView.loadUrl(shareInviteBean.getLink() + "&phone=true");
            }
            loadData("002");
            isNeedRefresh = false;
        }
    }

    /**
     * 提示完成个人信息
     */
    public void showFinishInfomationDialog(Context context, String title, String confirm, String cancel, final boolean isFocus) {
        final ConfirmLoginDialog confirmDialog = new ConfirmLoginDialog(context, title, confirm, cancel, R.layout.pop_tologin);
        confirmDialog.show();
        confirmDialog.setClicklistener(new ConfirmLoginDialog.ClickListenerInterface() {
            @Override
            public void doConfirm() {
                Intent intent = new Intent(mActivity, InformationActivity.class);
                intent.putExtra("isForShare", isFocus);
                confirmDialog.dismiss();
                mActivity.startActivity(intent);
            }
            @Override
            public void doCancel() {
                confirmDialog.dismiss();
            }
        });
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_share:
                if (shareInviteBean != null && !TextUtils.isEmpty(shareInviteBean.getName()) && !TextUtils.isEmpty(shareInviteBean.getDomain())) {
                    showShare(shareInviteBean.getName());
                } else if (shareInviteBean != null && TextUtils.isEmpty(shareInviteBean.getName())){
                    showFinishInfomationDialog(this, "请完善您请柬信息", "完善", "取消",false);
                } else if (shareInviteBean != null && TextUtils.isEmpty(shareInviteBean.getDomain())){
                    showFinishInfomationDialog(this, "请完善您婚礼域名!", "完善", "取消",true);
                }
                break;
            case R.id.llay_guests:
                Intent intent = new Intent(this, GuestsActivity.class);
                intent.putExtra("shareInviteBean", shareInviteBean);
             webView.loadUrl("javascript:autoPlayMusic("+"false"+")");
                startActivity(intent);
                break;
            case R.id.llay_information:
                startActivity(new Intent(this, InformationActivity.class));
              webView.loadUrl("javascript:autoPlayMusic("+"false"+")");
                break;
            case R.id.llay_write_story:
                startActivity(new Intent(this, WriteStoryActivity.class));
                webView.loadUrl("javascript:autoPlayMusic("+"false"+")");
                break;
            case R.id.llay_theme_settings:
                startActivity(new Intent(this, ThemeSettingsActivity.class));
               webView.loadUrl("javascript:autoPlayMusic("+"false"+")");
                break;
            case R.id.img_back:
                onBackPressed();
                break;
            case R.id.img_music:
                break;
        }
    }


    @Override
    public void onBackPressed() {
        if (webView!=null){
            webView.loadUrl("javascript:autoPlayMusic("+"false"+")");
            webView.destroy();
        }
        finish();
    }

    private BroadcastReceiver myReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            isNeedRefresh = true;
            if(isResume){
                setData();
            }
        }

    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (webView!=null){
            webView.loadUrl("javascript:autoPlayMusic("+"false"+")");
            webView.destroy();
        }
        unregisterReceiver(myReceiver);
    }

    /**
     * 一键分享
     */
    private void showShare(String title) {
        String url = "", description = "";
        ShareInviteBean.DataBean picData = null;
        if (shareInviteBean != null) {
            url = shareInviteBean.getDomain();//点开后网址链接地址
            description = shareInviteBean.getContent();
            picData = shareInviteBean.getData();
            if (picData == null || TextUtils.isEmpty(picData.getNvc_Pic())) {
                copyToSD(this);//这个拷贝 的是应用图标在下边用到了
            }
        }
        ShareSDK.initSDK(this);
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();
        oks.setTitle(title);
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
        oks.setTitleUrl(url);
        // text是分享文本，所有平台都需要这个字段
        oks.setText(description);
        if (picData != null && !TextUtils.isEmpty(picData.getNvc_Pic())) {
            oks.setImageUrl(picData.getNvc_Pic());
        } else {
            // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
            File dbFile = FileUtil.getDefaultFile("invitation66.jpg");
            oks.setImagePath(dbFile.getPath());//确保SDcard下面存在此张图片
        }
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl(url);
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment(description);
        oks.setSiteUrl(url);
        // 启动分享GUI
        oks.show(this);
        Log.i("1111111", "showShare: ");
    }

    /**
     * 把raw的图片存到SD卡上
     */
    public static void copyToSD(Context context) {
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            File dbFile = FileUtil.getDefaultFile("invitation66.jpg");
            if (!dbFile.exists()) {
                is = context.getResources().openRawResource(
                        R.raw.share_invitation);
                fos = new FileOutputStream(dbFile);
                byte[] buffer = new byte[8 * 1024];// 8K
                while (is.read(buffer) > 0)// >
                {
                    fos.write(buffer);
                }
            }
        } catch (Exception e) {
        } finally {
            try {
                if (is != null) {
                    is.close();
                }

                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 设置应用字号不受系统字号设置的影响
     */
    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }

}